package org.seamon.management.util.security;

import org.seamon.management.pojo.entity.User;
import org.seamon.management.service.UserService;
import org.seamon.management.util.enums.ErrorCodeEnum;
import org.seamon.management.util.exception.BusinessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author Simon
 */
public class UserContext {

    /**
     * 获取当前操作用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return "游客";
        }
        Object principal = authentication.getPrincipal();

        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        return principal.toString();
    }

    /**
     * 获取当前操作用户
     */
    public static User getCurrentUser() {
        String currentUsername = getCurrentUsername();
        if ("游客".equals(currentUsername)) {
            throw new BusinessException(ErrorCodeEnum.UNAUTHORIZED);
        }
        UserService userService = ApplicationContextHolder.getBean(UserService.class);
        return userService.getByUsername(currentUsername);
    }

}
